package com.ants.project.fast.site.tags;

import com.alibaba.fastjson.JSON;
import com.ants.project.fast.site.mapper.SqlMapper;
import freemarker.core.Environment;
import freemarker.template.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

/**
 * @author liushun
 * @version 1.0
 * @Date 2016-01-18
 */
public class SqlTag implements TemplateDirectiveModel {

    private final Logger logger = LoggerFactory.getLogger("SqlTag");

    @Autowired
    private SqlMapper sqlMapper;


    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            String check = RandTagProperty(params);
            if("".equals(check)){
                Map linkmap = linkMapSql(params);
                List<Map> list = sqlMapper.getDataList(linkmap);
                env.setVariable("list", DEFAULT_WRAPPER.wrap(list));
                // 指令内容体不为空
                if (body != null) {
                    if(Integer.parseInt(params.get("debug").toString())==1)
                        body.render(env.getOut().append("<div style='color:red'>sql dubug: select "+ linkmap.get("fields")
                                +" from "+linkmap.get("tables")
                                +" where "+linkmap.get("condition")+" "
                                +linkmap.get("postfix")+"</div>"));
                    else
                        body.render(env.getOut());
                } else {
                    throw new RuntimeException("missing body");
                }
            }else {
                Writer out = env.getOut();
                out.write("错误："+ check);
                body.render(out);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验标签里面的属性
     * @param map{
     *      data: 接受值名称
     *      tables: 表名称
     *      fields: 字段
     *      conditions: 条件
     *      debug: 是否调试
     * }
     * @return
     */
    public String RandTagProperty(Map map){
        if(map.get("data")==null||"".equals(map.get("data")))
            return "data 数据对象属性不能为空";
        else if(map.get("tables")==null||"".equals(map.get("tables")))
            return "tables 表名称属性不能为空";
        else if("".equals(map.get("fields")))
            return "fields 字段属性要么省略要么填写";
        else if("".equals(map.get("conditions")))
            return "conditions 条件属性要么省略要么填写";
        else if(map.get("debug")==null)
            return "debug 调试属性要么省略是0或1";
        else
            return "";
    }
    /**
     * 拼接成sql语句
     * 主要由字段 fields
     * 表名称 tables
     * 条件 condition
     * 后缀条件 postfix
     * @return
     */
    public Map linkMapSql(Map params){
        Map map = new HashMap();
        String[] tables = String.valueOf(params.get("tables")).split(",");
        Object fields = params.get("fields");
        Object conditions = params.get("conditions");
        map.put("fields", fields==null||fields.equals("")?"*":fields);
        //for(String table:tables)
        map.put("tables", params.get("tables"));
        if(conditions!=null&&!conditions.equals("")) {
            String condition = String.valueOf(conditions).split("#")[0];
            map.put("condition",condition.replaceAll("&", " and ").replaceAll("\\|", "or"));
            String postfix =String.valueOf(conditions).split("#")[1];
            map.put("postfix",postfix.replaceAll("&", " ").replaceAll("order=", "order by ").replaceAll("limit=", " limit "));
        }
        return map;
    }
}
